<?php

namespace app\admin\model\hotel;

use app\admin\model\Area;
use think\Model;
use traits\model\SoftDelete;
use fast\Http;

class Hotel extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'hotel';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [

    ];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            if (!$row['weigh']) {
                $pk = $row->getPk();
                $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
            }
        });
    }

    public function getcity($lat,$lng)
    {

        $url = 'https://restapi.amap.com/v3/geocode/regeo';

        $data = [
            'output'=>'json',
            'key'=>'84188bdb74e00130b9520d94d13f6936',
            'location'=>$lng.','.$lat
        ];

        $res = Http::get($url,$data);

        $res = json_decode($res);

        if ($res->status!=1){
            return [
                'code'=>0,
                'data'=>$data,
                'msg'=>'获取地址失败'
            ];
        }
        $district = $res->regeocode->addressComponent->district;
        $citycode = $res->regeocode->addressComponent->citycode;

        $district_info = Area::get(['name'=>$district,'level'=>3,'code'=>$citycode]);

        if (!$district_info){
            return [
                'code'=>0,
                'data'=>$data,
                'msg'=>'获取地址失败'
            ];
        }

        $city_info = Area::get($district_info->pid);

        $province_info = Area::get($city_info->pid);

        $data = [
            'province_id'=>$province_info->id,
            'city_id'=>$city_info->id,
            'district_id'=>$district_info->id,
        ];

        return [
            'code'=>1,
            'data'=>$data,
            'msg'=>'success'
        ];
    }

}
